package com.hzhr.extdevice.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.util.StringUtils;

public class JsonUtil {
	/**
	 * 对象转json字符串
	 * @title Obj2Json
	 * @description
	 * @param obj：对象
	 * @return json字符串
	 * @throws JsonProcessingException
	 * @author 48310
	 * @date 2017年11月3日
	 * @see 
	 *
	 */
	public static String Obj2Json(Object obj) {
		try {
			if (obj == null) return null;
			ObjectMapper mapper = new ObjectMapper();
			return mapper.writeValueAsString(obj);
		} catch (Exception e) {
			throw new  RuntimeException(e);
		}
	}
	
	public static <T> T Obj2T(Object obj, Class<T> clazz) {
		try {
			if (obj == null) {
				return null;
			}
			ObjectMapper mapper = new ObjectMapper();
			String json = mapper.writeValueAsString(obj);
			T t = mapper.readValue(json, clazz);
			return t;
		} catch (Exception e) {
			throw new  RuntimeException(e);
		}
	}
	
	public static <T> T Json2Obj(String json, Class<T> clazz) {
		if (StringUtils.isEmpty(json)) return null;
		try {
			ObjectMapper mapper = new ObjectMapper();
			return mapper.readValue(json, clazz);
		} catch (Exception e) {
			throw new  RuntimeException(e);
		}
	}
	
	
}
